import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import { errorAlert, errorModal } from '../modules/system';

export default function errorMiddleware(_ref) {
  var dispatch = _ref.dispatch;

  return function (next) {
    return function (action) {
      var error = action.error,
          payload = action.payload,
          rest = _objectWithoutProperties(action, ['error', 'payload']);

      var meta = _extends({
        suppressError: false,
        errors: false,
        errorTrigger: 'ALERT'
      }, rest.meta);
      var errors = meta.errors;

      // If there's no error or we need to hide the error message then continuing middlware chain
      if (!error) {
        return next(action);
      }

      var _payload$status = payload.status,
          status = _payload$status === undefined ? '' : _payload$status,
          _payload$statusText = payload.statusText,
          statusText = _payload$statusText === undefined ? 'An unexpected error occurred.' : _payload$statusText;

      var errorMessage = void 0;

      // Action creators could define their custom error messages depending on HTTP status in `meta`
      if (typeof payload.formatErrorMessage === 'function') {
        errorMessage = payload.formatErrorMessage(errors);
      } else if (errors && errors[status]) {
        errorMessage = errors[status];
      } else if (typeof payload === 'string') {
        errorMessage = payload;
      } else {
        errorMessage = (status + ' ' + statusText).trim();
      }

      var errorAction = meta.errorTrigger === 'ALERT' ? errorAlert : errorModal;

      !meta.suppressError && dispatch(errorAction(errorMessage));

      return next(_extends({}, action, { errorMessage: errorMessage, meta: meta }));
    };
  };
}